#include "lcd.h"

#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/mman.h>
#include <stdlib.h>

int *plcd = NULL;
int lcd_fd = -1;
int touch_fd = -1;

void lcd_draw_point(int i,int j,unsigned color)
{
    if(i>=0&&i<480&&j>=0&&j<800)
    {
        *(plcd+i*800+j) = color;
    }
}

/*
    画一个矩形
    x0,y0 起始点的坐标 左上角的坐标
    width 宽
    height 高
    color 颜色
*/
void lcd_draw_rectangle(int x0,int y0,int width,int height,unsigned color)
{
    for(int i = x0;i<x0+height;i++)
    {
        for(int j = y0;j<y0+width;j++)
        {
            //画点
            lcd_draw_point(i,j,color);
        }
    }
}

int Init_lcd()
{
     // 1.打开屏幕
    lcd_fd = open("/dev/fb0",O_RDWR);
    if(lcd_fd == -1)
    {
        perror("lcd open failed:");
        return -1;
    }
    // 2.映射(plcd定义成一个全局变量)
    plcd = mmap(NULL,800*480*4,PROT_EXEC|PROT_READ|PROT_WRITE,MAP_SHARED,lcd_fd,0);
    if(plcd == NULL)
    {
        perror("mmap failed:");
        close(lcd_fd);
        return -1;
    }
    //1.打开触摸屏
	touch_fd = open("/dev/input/event0",O_RDWR);
	if(touch_fd == -1)
	{
		perror("open touch failed:");
        close(lcd_fd);
		return -1;
	}
}

void unInit_lcd()
{
    //关闭触摸屏
    close(touch_fd);
    // 4.解映射
    munmap(plcd,800*480*4);
    // 5.关闭屏幕
    close(lcd_fd);
}

/*
    bmp_pathname:bmp图片路径
    x0,y0:显示图片的起始位置
*/
void display_bmp(char *bmp_pathname,int x0,int y0)
{
    //1.打开
   int bmp_fd = open(bmp_pathname,O_RDWR);
   if(bmp_fd == -1)
   {
        perror("bmp:");
   }
   //2.读取宽 高 色深
    int width = 0;
    lseek(bmp_fd,0x12,SEEK_SET);
    read(bmp_fd,&width,4);

    int height = 0;
    lseek(bmp_fd,0x16,SEEK_SET);
    read(bmp_fd,&height,4);

    int depth = 0;
    lseek(bmp_fd,0x1c,SEEK_SET);
    read(bmp_fd,&depth,2);

    printf("width = %d height = %d depth = %d\n",abs(width),abs(height),depth);

    //3.定义数组，再去读取像素点
    int total_bytes = abs(height) * abs(width)*(depth/8);
    char p[total_bytes];

    lseek(bmp_fd,0x36,SEEK_SET);
    read(bmp_fd,p,total_bytes);

    //4.解析像素数组的数据
    int count = 0;
    unsigned char a,r,g,b;
    unsigned color;
    for(int i = 0;i<abs(height);i++)
    {
        for(int j = 0;j<abs(width);j++)
        {
            b = p[count++];
            g = p[count++];
            r = p[count++];
            if(depth == 32)
            {
                a = p[count++];
            }
            else if(depth == 24)
            {
                a = 0;
            }
            
            //组装
            color = a<<24 | r<<16 | g<<8 | b;
            //画点
            lcd_draw_point(height>0?(abs(height)-1-i+x0)%480:(i+x0)%480,width>0?(j+y0)%800:(abs(width)-1-j+y0)%800,color);
        }
    }

    //5.关闭图片
    close(bmp_fd);
}

